package com.isp.common.utils;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 雪花算法工具
 *
 * @author Linsy
 */
public class SnowFlakeUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(SnowFlakeUtils.class);

    public static final SnowFlakeUtils instance = new SnowFlakeUtils();

    private Snowflake snowflake;

    /**
     * 获取雪花算法实例
     *
     * @return 雪花算法实例
     */
    public static SnowFlakeUtils getInstance() {
        return instance;
    }

    /**
     * 构造方法私有，使用单列方式
     */
    private SnowFlakeUtils() {
        long workerId;
        long datacenterId = 1000;
        try {
            // 根据ip生成转long后32取余数的作为workerId
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr()) % 32;
            datacenterId = datacenterId % 32;
            snowflake = IdUtil.getSnowflake(workerId, datacenterId);
        } catch (Exception e) {
            LOGGER.error("当前机器的workerId获取失败", e);
            workerId = NetUtil.getLocalhostStr().hashCode();
            LOGGER.error("当前机器workId:{}", workerId);
        }
    }

    /**
     * 获取id
     *
     * @return 雪花算法id
     */
    public String nextId() {
        return snowflake.nextIdStr();
    }


    public static void main(String[] args) {
        String nextId = SnowFlakeUtils.getInstance().nextId();
        System.out.println(nextId);
    }
}